package com.fingard.dsp.bank.directbank.bocom01;

import static com.fingard.io.FileHelper.existFile;
import static com.fingard.io.FileHelper.readFileText;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.dbobj.receipt.ReceiptData;
import com.fingard.dsp.bank.dbobj.receipt.ReceiptDataHelper;
import com.fingard.dsp.bank.directConfig.ReceiptProConfig;
import com.fingard.dsp.bank.directbank.bankInterface.IReceiptPro;
import com.fingard.dsp.bank.helpers.receipthelpers.DownReceiptFileHelper;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.ReqQryReceipt;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.RetAtsReceipt;
import com.fingard.dsp.bank.sepro.ReceiptPro;
import com.fingard.dsp.task.command.SyncReceipt;
import com.fingard.io.FileHelper;
import com.fingard.text.MFSHelper;
import com.fingard.text.StringHelper;

public class BOCOM01ReceiptPro extends BOCOM01Base implements IReceiptPro{

	@Override
	public RetAtsReceipt qryReceiptOneDay(ReceiptProConfig pConfig, ReqQryReceipt pReqReceipt, Date pOneDay)
			throws Exception {

		String qryDay8 = Format.Date8Format.format(pOneDay);
		String saveDirPathTemp = pConfig.getSaveSubDir(pReqReceipt.reqHeader, pOneDay) + File.separator + qryDay8 + File.separator + ReceiptPro.getTransID();
		String chkDay = "_"+qryDay8;
		//调用通用下载方法
		DownReceiptFileHelper downFileHelper = new DownReceiptFileHelper(this);
		downFileHelper.downAndUnZipFiles(saveDirPathTemp, chkDay);
		
		//调用提取pdf文件的方法
		getPdfFiles(pConfig, pReqReceipt, pOneDay, saveDirPathTemp);
		
		WriteBankLogLn("删除"+saveDirPathTemp);
        FileHelper.deleteRecursive(saveDirPathTemp);
        
		return null;
	}
	
	private void getPdfFiles(ReceiptProConfig pConfig, ReqQryReceipt pReqReceipt, Date pOneDay, String pReceiptDir){
		ReceiptDataHelper receiptHelper = null;//回单数据保存类，分区分表
		try{
        	receiptHelper = new ReceiptDataHelper(pReqReceipt.reqHeader.tenant, pOneDay);
        	File receiptDir = new File(pReceiptDir);
        	
        	int[] retVals = getPdfLoop(pConfig, pReqReceipt, pOneDay, receiptHelper, receiptDir);
        	//[0]总数 [1]新增 [2]已存在
            WriteBankLogLn("目录"+pReceiptDir+"\r\n遍历总数"+retVals[0]+"，新增"+retVals[1]+"条，已存在"+retVals[2]+"条");
            if(retVals[1]>0){
            	SyncReceipt.resetDelayCounter();
            }
        	
		}catch(Exception ex){
        	this.WriteBankLogLn(ex);
        }finally{
        	if(receiptHelper != null){
        		receiptHelper.close();
        	}
        }
	}
	
	/**下载的日期目录中提取该账号对应的html，再提取pdf
	 *
	 * */
	private int[] getPdfLoop(ReceiptProConfig pConfig, ReqQryReceipt pReqReceipt, Date pOneDay, ReceiptDataHelper pReceiptHelper, File pDir){
		int[] retVals = new int[3];
		retVals[0] = 0;//总pdf个数
		retVals[1] = 0;//新增
		retVals[2] = 0;//已存在
		
		File[] files = pDir.listFiles();
		
		String ownActNum = pDir.getName().split("_")[0];
		
		String collect_txt = pDir.getParent() + File.separator + pDir.getName().replace(".zip", "") + ".txt";
		Map<String,String[]> data = new ConcurrentHashMap<String,String[]>();
		//回单编号去匹配
        int curFieldNum = 10 ;
		if (existFile(collect_txt)) {
			WriteBankLogLn("开始匹配汇总文件:" + collect_txt);
            String fileContent = new String();
            fileContent = readFileText(collect_txt, "UTF-8");

            if(StringHelper.hasAnyChar(this.getBankConfig().getValueAsString("useNewReponsetxt"))){
                curFieldNum = Integer.valueOf(this.getBankConfig().getValueAsString("useNewReponsetxt"))-1;
            }

            StringBuilder curSbLog = new StringBuilder();
            ArrayList<String[]> curDataList = MFSHelper.getTextArray(fileContent, "|!", curFieldNum, files.length - 1, curSbLog);
            if (curSbLog.length() == 0) {
                //回单日期|!回单编号|!会计流水号|!序号|!付款人账号|!付款人户名|!收款人账号|!收款人户名|!交易金额|!借贷标志|!摘要|!附加信息
                for (int j = 1; j < curDataList.size(); j++) {
                	//匹配会计流水号
                    String[] curRowDataArr = curDataList.get(j);
                    String tranSeqNo = curRowDataArr[1];
                    data.put(tranSeqNo, curRowDataArr);
                }
            }else{
            	WriteBankLogLn("匹配汇总文件失败:" + curSbLog.toString());
            }
        }

    	for (File eachFile : files) {
    		try{
    			if(eachFile.isDirectory()){
        			int[] subVals = getPdfLoop(pConfig, pReqReceipt, pOneDay, pReceiptHelper, eachFile);
        			retVals[0] = retVals[0] + subVals[0];
        			retVals[1] = retVals[1] + subVals[1];
        			retVals[2] = retVals[2] + subVals[2];
        		}
    			String eachName = eachFile.getName();
                if (eachName.toLowerCase().endsWith(".pdf")) {
                	retVals[0] = retVals[0] + 1;
                	//1202020209900311818_20191118_19322000001.PDF
                	String[] nameAndExt = StringHelper.splitFileNameAndExt(eachName);
                	String[] nameSp = nameAndExt[0].split("_");
                	if(nameSp.length < 2){
                		WriteBankLogLn("文件名"+eachName+"不符合预期格式");
                		continue;
                	}
                	ReceiptData eachData = new ReceiptData();
                    eachData.istNbr = nameSp[1];
                    eachData.ownAct = ownActNum;
                    eachData.cur=getBankConfig().getMapValueByKey("elereceiptAccountInfo", ownActNum);
                    eachData.setBusDate(pOneDay);
                    //重命名
                    String renameToPath = pConfig.getSaveSubDir(pReqReceipt.reqHeader, pOneDay) + File.separator + String.valueOf(eachData.busDate) + File.separator + eachData.ownAct;
                    FileHelper.mkdirsIfNotExists(renameToPath);
                    renameToPath += File.separator + eachFile.getName();
                    File destFile = new File(renameToPath);
                    boolean reResult;
                    if(destFile.exists()){
                    	reResult = true;
                    }else{
                    	reResult = eachFile.renameTo(destFile);
                    }
                    if(reResult){
                    	eachData.localFile = StringHelper.getRelativePath(destFile.getAbsolutePath(), pConfig.localSaveMainDir);
                    	eachData.srcFile = eachFile.getName();
                        eachData.busRef = nameSp[1];
                        eachData.receiptNo = nameSp[2];
                        eachData.bank = "301";
                        eachData.srcSys = "BOCOM01";
                        
                        if(data.containsKey(eachData.receiptNo)){
                        	String[] receiptData = data.get(eachData.receiptNo);
                        	if(receiptData.length>5){
                        		eachData.moneyWay = receiptData[curFieldNum-2].equals("借方")? "1":"2";
                        		eachData.oppActName = receiptData[curFieldNum - 4];
                        		eachData.oppActNum = receiptData[curFieldNum - 5];
                        		eachData.bnkSeqNo = receiptData[2];
                        		eachData.amount = new BigDecimal(receiptData[curFieldNum-3]);
                        	}
                        }
                        
                        if(!String.valueOf(eachData.busDate).equals(nameSp[0])){
                        	WriteBankLogLn("提取的日期"+nameSp[0]+"不符合预期"+String.valueOf(eachData.busDate)+"，回单文件名:" + eachFile.getName());
                        	eachData.downInfo = nameSp[0]+"-文件中提取的日期";
                        }
                        eachData.downState = "2";
                        eachData.downTime = new Date();
                        int inRe = pReceiptHelper.insertIfNotExist(eachData, true);
                        if(inRe>0){
                        	retVals[1] = retVals[1] + 1;
                        }else if(inRe == 0){
                        	retVals[2] = retVals[2] + 1;
                        }
                        WriteBankLogLn(eachData.receiptNo+"写入数据库，影响行数："+inRe);
                    }else{
                    	WriteBankLogLn(eachData.receiptNo+"重命名失败：\r\n"+eachFile.getAbsolutePath()+"\r\n重命名为：\r\n"+renameToPath);
                    }
                }
                
    		}catch(Exception ex){
    			WriteBankLogLn(ex, eachFile.getAbsolutePath());
    		}
    	}
    	return retVals;
	}

}
